package com.liupaik.pennmarketplace;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;


public class Sublets extends Activity {

	//private TextView listings;
	private Listings adapter;
	private ListView list;
	List<Listing> listings;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.sublets);

		//listings = (TextView)findViewById(R.id.listings);

		Button btnRefresh = (Button)findViewById(R.id.refresh_button);
		btnRefresh.setOnClickListener(new OnClickListener() {
			public void onClick(View view) {
				//				final ProgressDialog pd = ProgressDialog.show(getDialogContext(), "", "Refreshing...", true);
				//				new Thread() {
				//					public void run() {
				//						try {

				populateList();
				adapter.notifyDataSetChanged();

				//						}
				//						catch (Exception e){
				//							Log.e("tag",e.getMessage());
				//						}
				//						pd.dismiss();
				//					}
				//				}.start();
			}
		});

		populateList();
		makeListClickable();
	}

	private Context getDialogContext() {
		Context context;
		if (getParent() != null) context = getParent();
		else context = this;
		return context;
	}

	private void populateList(){
		listings = new ArrayList<Listing>();
		String result = getListings("2");
		if(result.equals("Error in connecting...")){
			new AlertDialog.Builder(getParent())
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();
		}
		else if (result.equals("Error in obtaining data...")){
			new AlertDialog.Builder(getParent())
			.setMessage(result)  
			.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
				}
			})
			.show();
		}
		else{
			list = (ListView)findViewById(R.id.list);
			try{
				JSONArray jArray = new JSONArray(result);
				for(int i=jArray.length()-1;i>=0;i--){
					JSONObject json_data = jArray.getJSONObject(i);
					String L_id = json_data.getString("L_id");
					String cat = json_data.getString("cat");
					String title = json_data.getString("title");
					String text = json_data.getString("text");
					String U_id = json_data.getString("U_id");
					String time = json_data.getString("time");
					//listings.append(L_id + " | " + cat + " | " + title + " | " + text + " | " + U_id + " | " + time + "\n");

					listings.add(new Listing(L_id,"",U_id,cat,title,text,time));
				}
			}
			catch(JSONException e){



				/*
				new AlertDialog.Builder(getParent())
				.setMessage("There are no Book listings yet. Go to Sell to make your own listing!")
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				})
				.show();*/


				//				Intent i = new Intent(Sublets.this, Blank.class);
				//        		View view = SubletsGroup.group.getLocalActivityManager()
				//				.startActivity("Blank", i
				//						.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
				//						.getDecorView();
				//				SubletsGroup.group.replaceView(view);


				Toast.makeText(
						getParent(),
						"There are no Sublets listings yet. Go to Menu -> Sell to make your own listings!",
						Toast.LENGTH_LONG)
						.show();




				Log.e("log_tag", "Error parsing data "+e.toString());

			}

			adapter = new Listings(Sublets.this, listings);
			list.setAdapter(adapter);
		}
	}






	private void makeListClickable(){
		list.setOnItemClickListener(new OnItemClickListener() {            	
			public void onItemClick(AdapterView<?> a, View v, int position, long id) {

				Listing entry = (Listing) a.getItemAtPosition(position);

				Intent i = new Intent(Sublets.this, Reply.class);
				i.putExtra("id", entry.getId());
				i.putExtra("U_id", entry.getU_id());
				i.putExtra("cat", entry.getCat());
				i.putExtra("title", entry.getTitle());
				i.putExtra("text", entry.getText());
				i.putExtra("time", entry.getTime());
				//startActivityForResult(i, 0);
				View view = SubletsGroup.group.getLocalActivityManager()
				.startActivity("Reply", i
						.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
						.getDecorView();
				SubletsGroup.group.replaceView(view);
			}
		});
	}

	public static final String LISTINGS = "http://www.upennakpsi.org/lololol/pennmarketplace/getlistings.php";

	private String getListings (String category) {

		InputStream is = null;

		String result = "";
		//LinkedList<String> listings = new LinkedList<String>();

		//the postings
		ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("cat",category));

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(LISTINGS);
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);            
			HttpEntity entity = response.getEntity();
			is = entity.getContent();                

		}catch(Exception e){
			//listings.add("Error in connecting...");
			result = "Error in connecting...";
			Log.e("log_tag", "Error in http connection "+e.toString());
			return result;
		}

		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result=sb.toString();
		}catch(Exception e){
			result = "Error in obtaining data...";
			Log.e("log_tag", "Error converting result "+e.toString());
			return result;
		}

		return result;
	}
}
